//
//  StrictElectionListViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/6.
//  Copyright © 2020 王洋. All rights reserved.
//

//#import "StoreCategoryListCell.h"

#import "StrictElectionCell.h"

#import "StrictElectionSortHeader.h"

#import "StoreDetailViewController.h"
#import "SearchViewController.h"
#import "MessageCenterViewController.h"
#import "StoreHotelDetailViewController.h"
#import "StrictElectionListViewController.h"

@interface StrictElectionListViewController ()<UITableViewDelegate, UITableViewDataSource>


@property (nonatomic, strong)UITableView *tableview;

@property (nonatomic, strong) NSMutableArray <CommonSellerModule *>*dataArray;


@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation StrictElectionListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
//    [self refreshParam];
    [self request_storeList];
}

//- (void)refreshParam {
//    self.pageSize = 20;
//    self.pageNum = 1;
//}

- (void)initView {
    
    self.title = @"严选商家";

    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];

    [self.tableview reloadData];
    
    [self initViewAction];
    
    UIButton *imBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    imBtn.frame = CGRectMake(0,0,40,30);
    [imBtn setImage:[UIImage imageNamed:@"yanxuan_xiaoxi"] forState:UIControlStateNormal];
    [imBtn addTarget:self action:@selector(goIm) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *imItem = [[UIBarButtonItem alloc] initWithCustomView:imBtn];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0,0,40,30);
    [searchBtn setImage:[UIImage imageNamed:@"yanxuan_search"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(goSearch) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];

    self.navigationItem.rightBarButtonItems =@[imItem,searchItem];
    
    [RACObserve([TT_MessageManager manager], totalUnReadCount) subscribeNext:^(id x) {
        if ([TT_MessageManager manager].totalUnReadCount > 0) {
            imBtn.badgeValue = [NSString stringWithFormat:@"%d",[TT_MessageManager manager].totalUnReadCount];
            imBtn.badgeBGColor = [UIColor redColor];
        } else {
            imBtn.badgeValue = @"";
            imBtn.badgeBGColor = [UIColor clearColor];
        }
    }];
}

- (void)initViewAction {
    

}

- (void)goIm {
    
    MessageCenterViewController *vc = [[MessageCenterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)goSearch {
    
    SearchViewController *vc = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 110;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark sectionheader
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    StrictElectionSortHeader *headView  =  [[NSBundle mainBundle] loadNibNamed:@"StrictElectionSortHeader"owner:nil options:nil].firstObject;
    return  headView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return  [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [StrictElectionCell calculateHeight];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([self.dataArray[indexPath.row].classId isEqualToString:Store_Category_Hotel]) {

        StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
        vc.storeId = self.dataArray[indexPath.row].sellerId;
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        StoreDetailViewController *vc = [[StoreDetailViewController alloc] init];
        vc.storeId = self.dataArray[indexPath.row].sellerId;
        [self.navigationController pushViewController:vc animated:YES];
    }

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    StrictElectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StrictElectionCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    return cell;
}


- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);

        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"StrictElectionCell" bundle:nil] forCellReuseIdentifier:@"StrictElectionCellID"];

        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
//            [weakSelf refreshParam];
            [weakSelf request_storeList];
        }];

//        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
//            weakSelf.pageNum ++;
//            [weakSelf request_storeList];
//        }];
        
    }
    return _tableview;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

//查询严选商家列表
- (void)request_storeList {

    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:[TTUserModel sharedObject].cityId forKey:@"sellerCityId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_StrictStore];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSArray *list = [data valueForKey:@"data"];
                
                if ([list isKindOfClass:[NSArray class]]) {
                    
                    weakSelf.dataArray = @[].mutableCopy;
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *listDic = list[i];
                        if ([listDic isKindOfClass:[NSDictionary class]]) {
                            CommonSellerModule *model = [CommonSellerModule modelWithDictionary:list[i]];

                            NSDictionary *sellerQualityAuthentication = [listDic valueForKey:@"sellerQualityAuthentication"];
                            model.sellerQualityAuthentication = [CommonQualityTagModel modelWithDictionary:sellerQualityAuthentication];
                            
                            if (model.lat > 0 && model.lng > 0) {
                                model.distance = [Utilities calculateStart:CLLocationCoordinate2DMake([TTUserModel sharedObject].latitude, [TTUserModel sharedObject].longitude) end:CLLocationCoordinate2DMake(model.lat,model.lng)];
                            }
                            
                            NSArray *coverPaths = [listDic valueForKey:@"coverPaths"];
                            
                            if ([coverPaths isKindOfClass:[NSArray class]]) {
                                model.coverPaths = @[].mutableCopy;
                                for (int j = 0; j < coverPaths.count; j++) {
                                    NSDictionary *coverPathsDic = coverPaths[j];
                                    CommonImageModel *imgModel = [CommonImageModel modelWithDictionary:coverPathsDic];
                                    [model.coverPaths addObject:imgModel];
                                }
                            }
                            
                            [weakSelf.dataArray addObject:model];
                        }
                    }
                    [weakSelf.tableview reloadData];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
    
}

@end
